﻿using System;
using System.Collections.Generic;
using System.Linq;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Logic;
using LFloatMath.Math;
using Sirenix.Utilities.Editor;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class BattleMapWindow : EditorWindow
    {
        private static BattleMapWindow _instance;

        public static BattleMapWindow Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = CreateWindow<BattleMapWindow>("BattleMap");
                }

                return _instance;
            }
        }

        [MenuItem("GameEditor/BattleDebug/BattleMapWindow", false, 100)]
        public static void Open()
        {
            Instance.Show();
        }

        private void OnInspectorUpdate()
        {
            Repaint();
        }

        public Vector2Int startpos;
        public Vector2Int endpos = new Vector2Int(50, 50);

        public int cellRadius = 15;

        public List<LVector2Int> fakePath = new List<LVector2Int>();

        private void OnGUI()
        {
            if (!EditorApplication.isPlaying)
            {
                return;
            }
            Battle battle = null;
            if (SBattleLogicModule.Instance.battleMap.Count > 0)
            {
                battle = SBattleLogicModule.Instance.battleMap.First((pair) => true).Value;
            }

            if (battle == null)
            {
                GUILayout.Label("未找到战斗实例");
                return;
            }

            var map = battle.playCtrl?.mapCtrl?.Map;
            if (map == null)
            {
                return;
            }

            var nLen1 = map.GetLength(0);
            var nLen2 = map.GetLength(1);
            EditorGUILayout.BeginVertical(GUILayout.Height(150));
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("开始");
                this.startpos.x = EditorGUILayout.IntSlider("x", this.startpos.x, 0, nLen1);
                this.startpos.y = EditorGUILayout.IntSlider("y", this.startpos.y, 0, nLen2);
                EditorGUILayout.EndVertical();
                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("结束");
                this.endpos.x = EditorGUILayout.IntSlider("x", this.endpos.x, 0, nLen1);
                this.endpos.y = EditorGUILayout.IntSlider("y", this.endpos.y, 0, nLen2);
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndHorizontal();

                this.cellRadius = EditorGUILayout.IntField("格子半径", this.cellRadius);
            }
            EditorGUILayout.EndVertical();
            var fInsideRaduis = this.cellRadius * 1.74f / 2; // 六边形内径，用来鼠标悬浮显示坐标

            var nStart1 = Mathf.Clamp(this.startpos.x, 0, nLen1);
            var nStart2 = Mathf.Clamp(this.startpos.y, 0, nLen2);
            var nEnd1 = Mathf.Clamp(this.endpos.x, 0, nLen1);
            var nEnd2 = Mathf.Clamp(this.endpos.y, 0, nLen2);
            this.startpos.x = nStart1;
            this.startpos.y = nStart2;
            this.endpos.x = nEnd1;
            this.endpos.y = nEnd2;

            string rStrHold = "";
            Rect rHoldRect = default;
            var nHeight = nEnd2 - nStart2 + 1;
            var nWidth = nEnd1 - nStart1 + 1;
            var fMapHeight = nHeight * 1.74f * this.cellRadius / 2;
            var fMapWidth = nWidth * 3 * this.cellRadius;
            EditorGUILayout.BeginVertical(GUILayout.Height(fMapHeight), GUILayout.Width(fMapWidth));
            EditorGUILayout.BeginHorizontal(GUILayout.Height(fMapHeight), GUILayout.Width(fMapWidth));
            {
                for (int i = nStart2; i < nEnd2; i++)
                {
                    for (int j = nStart1; j < nEnd1; j++)
                    {
                        var rMapNode = map[j, i];
                        var x = j - nStart1;
                        var y = i - nStart2;
                        var defaultOffset = new Vector3(cellRadius, cellRadius + 150, 0);
                        float xOffset = i % 2 == 0 ? 0 : 1.5f; // 奇数行向右偏移
                        Vector3 hexCenter = new Vector3((x * 3 + xOffset) * cellRadius, fMapHeight - y * Mathf.Sqrt(3) / 2f * cellRadius, 0);
                        hexCenter += defaultOffset;
                        var rColor = (rMapNode.obstructType & BattleMapController.EObstructType.Role) > 0 ? Color.red :
                            (rMapNode.obstructType & BattleMapController.EObstructType.OutSide) > 0 ? Color.black : Color.gray;
                        if (this.fakePath.Contains(rMapNode.pos))
                        {
                            rColor = Color.green;
                        }
                        this.DrawHexagon(hexCenter, rColor);
                        if (Event.current.type == EventType.MouseDown)
                        {
                            var rMousePos = Event.current.mousePosition;
                            if ((rMousePos - new Vector2(hexCenter.x, hexCenter.y)).sqrMagnitude <=
                                fInsideRaduis * fInsideRaduis)
                            {
                                if (this.fakePath.Contains(rMapNode.pos))
                                {
                                    this.fakePath.Remove(rMapNode.pos);
                                }
                                else
                                {
                                    this.fakePath.Add(rMapNode.pos);
                                }
                            }
                        }
                        if (Event.current.type == EventType.Repaint)
                        {
                            var rMousePos = Event.current.mousePosition;
                            if ((rMousePos - new Vector2(hexCenter.x, hexCenter.y)).sqrMagnitude <=
                                fInsideRaduis * fInsideRaduis)
                            {
                                var rWorldPos = battle.playCtrl?.mapCtrl.MapToWorldPos(new(rMapNode.x, rMapNode.y)) ?? LVector2.zero;
                                rStrHold = $"({rMapNode.x},{rMapNode.y}):[{rMapNode.obstructUnitID},{rWorldPos}]";
                                // 在特定位置显示说明文字
                                rHoldRect = new Rect(hexCenter.x + 10f, hexCenter.y, 200f, 20f);
                            }
                        }
                        // Rect colorBlockRect = EditorGUILayout.GetControlRect(GUILayout.Width(nWidth), GUILayout.Height(nWidth));
                        // EditorGUI.DrawRect(colorBlockRect, (rMapNode.obstructType & BattleMapController.EObstructType.Role) > 0 ? Color.red : 
                        //     (rMapNode.obstructType & BattleMapController.EObstructType.OutSide) > 0 ? Color.black : Color.gray);

                        // 添加鼠标悬停区域
                        // EditorGUIUtility.AddCursorRect(colorBlockRect, MouseCursor.Link);
                        //
                        // // 判断鼠标是否悬停在色块上
                        // if (colorBlockRect.Contains(Event.current.mousePosition))
                        // {
                        //     rStrHold = $"{i},{j}:{map[i,j].obstructUnitID}";
                        //     // 在特定位置显示说明文字
                        //     rHoldRect = new Rect(colorBlockRect.xMax + 10f, colorBlockRect.y, 200f, 20f);
                        // }
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
            if (!string.IsNullOrEmpty(rStrHold))
            {
                GUI.color = Color.white;
                EditorGUI.LabelField(rHoldRect, rStrHold);
            }
        }

        /// <summary>
        /// 绘制一个六边形，并范围内部最大方形rect
        /// </summary>
        /// <param name="center"></param>
        /// <param name="color"></param>
        private void DrawHexagon(Vector3 center, Color color)
        {
            Vector3[] hexagonVertices = new Vector3[6];

            // 计算六边形的6个顶点
            for (int i = 0; i < 6; i++)
            {
                float angle_deg = 60 * i; // 每个角度相差60度
                float angle_rad = Mathf.PI / 180 * angle_deg;
                hexagonVertices[i] = new Vector3(
                    center.x + Mathf.Cos(angle_rad) * cellRadius,
                    center.y + Mathf.Sin(angle_rad) * cellRadius,
                    center.z);
            }

            // 绘制六边形的边
            for (int i = 0; i < hexagonVertices.Length; i++)
            {
                Vector3 current = hexagonVertices[i];
                Vector3 next = hexagonVertices[(i + 1) % hexagonVertices.Length]; // 下一个顶点，最后一个连接到第一个
                Handles.DrawLine(current, next);
            }

            // 可选：绘制填充颜色（例如一个半透明的颜色）
            Handles.color = color; // 设置填充颜色
            Handles.DrawAAConvexPolygon(hexagonVertices); // 绘制填充六边形
            Handles.color = Color.green; // 恢复线条颜色
        }
    }
}